﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;
using UnityEngine;

namespace Player
{
    [Serializable]
    public class Test
    {
        public string prefabId;
        public float guid;

        public Dictionary<string, object> data;
        // public Vector3 position;
    }

    public class TestFileReadWrite : MonoBehaviour
    {
        private string savePath => Application.persistentDataPath + "/test.dat";

        private void Start()
        {
            jsonTest();
        }

        private void jsonTest()
        {
            Test spawnData = new Test();
            var spawnDataData = new Dictionary<string, object>();
            spawnDataData["prefabId"] = "11";
            spawnData.data = spawnDataData;
            // spawnData.position = new Vector3(1, 2, 3);
            spawnData.guid = Guid.NewGuid().GetHashCode();
            spawnData.prefabId = "11";
            var serializeObject = JsonConvert.SerializeObject(spawnData);
            var json = JsonUtility.ToJson(spawnData);
        }

        private void readWriteFile()
        {
            Test spawnData = new Test();
            var spawnDataData = new SerializableDic<string, object>();
            spawnDataData["prefabId"] = "11";
            // spawnData.data = spawnDataData;
            // spawnData.position = new Vector3(1, 2, 3);
            using (FileStream stream = new FileStream(savePath, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, JsonUtility.ToJson(spawnData));
            }

            using (FileStream stream = new FileStream(savePath, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                spawnData = JsonUtility.FromJson<Test>((string)formatter.Deserialize(stream));
            }
        }
    }
}